package net.caidingke.shepherd.controller;

import io.ebean.PagedList;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.caidingke.shepherd.controller.base.BasicController;
import net.caidingke.shepherd.domain.user.User;
import net.caidingke.shepherd.domain.user.request.UserRequest;
import net.caidingke.shepherd.exception.NotFoundException;
import net.caidingke.shepherd.profile.CurrentUser;
import net.caidingke.shepherd.security.SecurityUtils;
import net.caidingke.shepherd.service.UserService;
import net.caidingke.shepherd.utils.code.validatecode.IVerifyCodeGen;
import net.caidingke.shepherd.utils.code.validatecode.SimpleCharVerifyCodeGenImpl;
import net.caidingke.shepherd.utils.code.validatecode.VerifyCode;
import net.caidingke.shepherd.utils.constant.GlobalConfig;
import net.caidingke.shepherd.utils.result.Result;
import net.caidingke.shepherd.utils.result.ResultPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户
 *
 * @author bowen
 */
@RestController
@Slf4j
@RequestMapping(value = GlobalConfig.API_PRE_FIX)
public class UserController extends BasicController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @ApiOperation(value = "获取图片验证码")
    @GetMapping("/verifyCode")
    public Result verifyCode(HttpServletRequest request, HttpServletResponse response) {
        IVerifyCodeGen iVerifyCodeGen = new SimpleCharVerifyCodeGenImpl();
        try {
            VerifyCode verifyCode = iVerifyCodeGen.generate(80, 28);
            request.getSession().setAttribute("VerifyCode", verifyCode.getCode());
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/jpeg");
            response.getOutputStream().write(verifyCode.getImgBytes());
            response.getOutputStream().flush();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return ok();
    }

    @PostMapping(value = "/register")
    public Result<User> register(@RequestBody UserRequest userRequest, HttpServletRequest request) {
        return ok(userService.register(userRequest));
    }

    @GetMapping("/me")
    public Result<User> me(@CurrentUser User user) {
        return ok(user);
    }

    @GetMapping("/users")
    public ResultPage<User> users(int page, int pageSize) {
        PagedList<User> pagedList = userService.findUsers(page, pageSize);
        return ok(pagedList.getList(), pagedList.getPageIndex(), pagedList.getPageSize(), pagedList.getTotalCount());
    }

    @GetMapping("/user/{id}")
    public Result<User> byId(@PathVariable(value = "id") Long id) {
        return ok(userService.byId(id).orElseThrow(NotFoundException::new));
    }

    @PutMapping("/user/modifyPassword")
    public Result<User> modifyPassword(@CurrentUser User user, @RequestParam Long userId, @RequestParam String password) {
        return ok(userService.modifyPassword(user, userId, password).orElseThrow(NotFoundException::new));
    }

    @GetMapping("/user/retry")
    public Result retry() throws Exception {
        userService.retryTest();
        return ok();
    }

    @PostMapping("/authenticate")
    public void authenticate(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (SecurityUtils.isAuthenticated()) {
            response.setStatus(200);
        } else {
            response.sendError(401, "Authentication failed");
        }
    }

    @PostMapping(value = "/login")
    public void login(HttpServletRequest request, String username, String password) throws ServletException {
        request.login(username, password);
    }

    @PostMapping("/logout")
    public void logout(HttpServletRequest request) throws ServletException {
        request.logout();
    }

}
